package com.mxpio.erp.purchase.service.impl;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.inventory.entity.SupplyChain;
import com.mxpio.erp.common.plan.entity.PurchasePlan;
import com.mxpio.erp.common.plan.service.PurchasePlanService;
import com.mxpio.erp.common.purchase.entity.BuyRequestOrder;
import com.mxpio.erp.common.purchase.entity.BuyRequestOrderLine;
import com.mxpio.erp.common.purchase.entity.Supply;
import com.mxpio.erp.common.purchase.service.BuyRequestOrderService;

import com.mxpio.erp.common.technology.entity.Item;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional(readOnly = true)
public class BuyRequestOrderServiceImpl extends BaseServiceImpl<BuyRequestOrder> implements BuyRequestOrderService {

    @Autowired
    private PurchasePlanService purchasePlanService;
    @Override
    @Transactional//从采购计划，转换为请购单
    public Result<Object> convertBROFromPPlan(List<PurchasePlan> planList){
        if (planList==null || planList.size()==0){
            return Result.error("提交数据为空");
        }
        List<String> itemCodes = planList.stream().map(PurchasePlan::getItemCode).collect(Collectors.toList());
        List<Item> dbItems = JpaUtil.linq(Item.class).in("itemCode", itemCodes).list();
        Map<String, Item> dbItemsMap = JpaUtil.index(dbItems, "itemCode");//查询提交数据中的物料
        List<SupplyChain> chains = JpaUtil.linq(SupplyChain.class)
                .collect("pnCode", Supply.class,"pnCode").in("itemCode", itemCodes).equal("defaultSupply","1").list();
        Map<String, SupplyChain> supplyChainMap = null;
        if (chains.size()>0){//关联默认供应商
            supplyChainMap = JpaUtil.index(chains, "itemCode");
        }

        BuyRequestOrder buyRequestOrder = convertFromPlan(planList, dbItemsMap,supplyChainMap);
        if (buyRequestOrder==null){
            return Result.error("提交数据中数据不完整（交付日期不能为空），物料不存在或者计划数量为空");
        }
        save(buyRequestOrder, new SmartCrudPolicyAdapter() {
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if (o instanceof BuyRequestOrderLine) {
                    BuyRequestOrder order = context.getParent();
                    ((BuyRequestOrderLine) o).setBizNo(order.getBizNo());
                    ((BuyRequestOrderLine) o).setLineStatus(OrderStatusEnums.BuyRequestLineStatus.CREATE.getStatusCode());
                }
                return true;
            }
        });
        planList.forEach(plan->{
            purchasePlanService.delete(PurchasePlan.class,plan.getPlanNo());//删除计划单
        });
        return Result.OK();
    }

    private BuyRequestOrder convertFromPlan(List<PurchasePlan> planList, Map<String, Item> dbItemsMap,Map<String, SupplyChain> supplyChainMap){
        List<BuyRequestOrderLine> addLines = new ArrayList<>();
        int lineno = 1;
        BuyRequestOrder bro = null;
        for (PurchasePlan plan:planList){
            if (plan.getQuantity()==null
                    ||plan.getQuantity().compareTo(BigDecimal.ZERO)==0
                    ||StringUtils.isBlank(plan.getItemCode())
                    ||plan.getDeliverDate()==null){
                return null;
            }
            Item item = dbItemsMap.get(plan.getItemCode());
            if (item==null){
                return null;
            }
            BuyRequestOrderLine line = new BuyRequestOrderLine();
            line.setLineNo(lineno+"");
            line.setCrudType(CrudType.SAVE);
            line.setQuantity(plan.getQuantity());
            line.setTrackingNo(plan.getPlanNo());
            line.setSuggestOrderDate(plan.getStartDate());
            line.setArriveDate(plan.getDeliverDate());
            line.setMemo(plan.getMemo());

            line.setItemCode(item.getItemCode());
            line.setItemGroupCode(item.getItemGroupCode());
            line.setDrawingNo(item.getDrawingNo());
            line.setItemName(item.getItemName());
            line.setItemSpec(item.getItemSpec());
            line.setUnitCode(item.getUnitCode());
            //设置默认供应商
            if (supplyChainMap!=null&& supplyChainMap.containsKey(plan.getItemCode())){
                SupplyChain supplyChain = supplyChainMap.get(plan.getItemCode());
                Supply supply = supplyChain.getSupply();
                if (supply!=null){
                    line.setPnCode(supply.getPnCode());
                    line.setPnName(supply.getPnName());
                }
            }

            addLines.add(line);
            lineno++;

            if (bro==null){
                bro = new BuyRequestOrder();
                bro.setCrudType(CrudType.SAVE);
                bro.setOrderDate(new Date());
                bro.setApplyMan(plan.getCreateBy());
                bro.setApplyDept(plan.getCreateDept());
                bro.setBizType("02");//ERP_PURC_BR_TYPE ‘01’:普通，‘02’:计划
                bro.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
            }
        }
        if (addLines.size()>0){
            bro.setBuyRequestOrders(addLines);
        }
        return bro;
    }

    @Override
    @Transactional
    public void setPnInfo(BuyRequestOrder buyRequestOrder) {//明细关联默认供应商
        List<BuyRequestOrderLine> buyRequestOrders = buyRequestOrder.getBuyRequestOrders();
        if (buyRequestOrders!=null&&buyRequestOrders.size()>0){
            Set<String> itemCodeSet = buyRequestOrders.stream().map(BuyRequestOrderLine::getItemCode).collect(Collectors.toSet());
            List<SupplyChain> chains = JpaUtil.linq(SupplyChain.class)
                    .collect("pnCode", Supply.class,"pnCode").in("itemCode", itemCodeSet).equal("defaultSupply","1").list();
            Map<String, SupplyChain> supplyChainMap = null;
            if (chains.size()>0){//关联默认供应商
                supplyChainMap = JpaUtil.index(chains, "itemCode");
                for (BuyRequestOrderLine line:buyRequestOrders){
                    if (StringUtils.isBlank(line.getPnCode())&& supplyChainMap.containsKey(line.getItemCode())){
                        SupplyChain supplyChain = supplyChainMap.get(line.getItemCode());
                        Supply supply = supplyChain.getSupply();
                        if (supply!=null){
                            line.setPnCode(supply.getPnCode());
                            line.setPnName(supply.getPnName());
                        }
                    }
                }
            }
        }
    }
}
